package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mydy.adapter.ActivityRankingAdapter;
import com.example.mydy.adapter.AnnouncementAdapter;
import com.example.mydy.adapter.HotRewardAdapter;
import com.example.mydy.model.ActivityData;
import com.example.mydy.model.Announcement;
import com.example.mydy.model.RewardTask;
import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.ActivityManager;
import com.example.mydy.utils.AchievementManager;
import com.example.mydy.utils.ImageUtils;
import com.example.mydy.utils.NetworkUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import de.hdodenhof.circleimageview.CircleImageView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements
        HotRewardAdapter.OnRewardClickListener,
        AnnouncementAdapter.OnAnnouncementClickListener {

    private static final String TAG = "MainActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_TOKEN = "token";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_USER_TYPE = "userType";
    private static final String KEY_USER_NICKNAME = "userNickname";
    private static final String KEY_BALANCE = "balance";
    private static final String KEY_LEVEL = "level";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";

    private ViewPager2 announcementPager;
    private RecyclerView hotRewardsRecyclerView;
    private AnnouncementAdapter announcementAdapter;
    private HotRewardAdapter hotRewardAdapter;
    private ActivityManager activityManager;
    private AchievementManager achievementManager;
    private UserInfo currentUser;
    private SharedPreferences prefs;

    // UI元素
    private TextView userNameText;
    private TextView userLevelText;
    private TextView userVipLevelText;
    private TextView userBalanceText;
    private TextView todayIncomeText;
    private TextView taskCountText;
    private TextView downlineIncomeText;
    private TextView activityStatusText;
    private View rankItem1, rankItem2, rankItem3;
    
    private LinearLayout todayIncomeLayout;
    private LinearLayout taskCountLayout;
    private LinearLayout downlineIncomeLayout;

    private boolean isNavigating = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置顶部状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        }

        if (isNavigating || checkDoubleLaunch()) {
            finish();
            return;
        }

        // 初始化SharedPreferences
        prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        activityManager = ActivityManager.getInstance(this);
        achievementManager = AchievementManager.getInstance(this);

        // 获取当前用户（在实际应用中应该使用登录后的用户信息）
        currentUser = activityManager.getCurrentUser();

        // 初始化视图
        initViews();
        
        // 设置底部导航
        setupBottomNavigation();
        
        // 设置快捷操作区域按钮点击
        setupQuickActions();
        
        // 加载用户数据
        loadUserData();
        loadAnnouncements();
        loadHotRewards();
        loadRankingPreview();
    }

    private void initViews() {
        // 初始化用户信息显示
        userNameText = findViewById(R.id.user_name);
        userLevelText = findViewById(R.id.user_level);
        userVipLevelText = findViewById(R.id.user_vip_level);
        userBalanceText = findViewById(R.id.user_balance);
        
        // 初始化数据概览显示
        todayIncomeText = findViewById(R.id.today_income);
        taskCountText = findViewById(R.id.task_count);
        downlineIncomeText = findViewById(R.id.downline_income);
        activityStatusText = findViewById(R.id.activity_status);
        
        // 初始化公告轮播
        announcementPager = findViewById(R.id.announcement_pager);
        
        // 初始化热门悬赏列表
        hotRewardsRecyclerView = findViewById(R.id.hot_rewards_recycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        hotRewardsRecyclerView.setLayoutManager(layoutManager);
        
        // 初始化排行榜项目
        rankItem1 = findViewById(R.id.rank_item_1);
        rankItem2 = findViewById(R.id.rank_item_2);
        rankItem3 = findViewById(R.id.rank_item_3);

        todayIncomeLayout = findViewById(R.id.today_income_layout);
        taskCountLayout = findViewById(R.id.task_count_layout);
        downlineIncomeLayout = findViewById(R.id.downline_income_layout);
        
        // 设置按钮点击事件
        findViewById(R.id.btn_settings).setOnClickListener(v -> {
            Log.d(TAG, "设置按钮被点击");
            Intent intent = new Intent(MainActivity.this, UserSettingsActivity.class);
            startActivity(intent);
        });
        
        // 提现按钮点击事件
        findViewById(R.id.btn_withdraw).setOnClickListener(v -> {
            Log.d(TAG, "提现按钮被点击");
            Intent intent = new Intent(MainActivity.this, com.example.mydy.withdraw.WithdrawActivity.class);
            startActivity(intent);
        });

        // 我的成就
        findViewById(R.id.btn_my_achievements).setOnClickListener(v -> {
            try {
                Intent intent = new Intent(MainActivity.this, AchievementsActivity.class);
                startActivity(intent);
                Log.d("MainActivity", "启动成就活动");
            } catch (Exception e) {
                Log.e("MainActivity", "启动成就活动失败: " + e.getMessage(), e);
                Toast.makeText(MainActivity.this, "无法打开成就界面: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupBottomNavigation() {
        // 使用BottomNavigationView替代单独的视图元素
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        
        // 设置底部导航菜单项选择监听器
        bottomNavigationView.setOnItemSelectedListener(item -> {
            // 获取选中的菜单项ID
            int itemId = item.getItemId();
            
            // 根据ID执行相应操作
            if (itemId == R.id.nav_home) {
                // 已在首页，无需操作
                return true;
            } else if (itemId == R.id.nav_advertisement) {
                // 跳转到广告列表页面
                startActivity(new Intent(MainActivity.this, AdvertisementListActivity.class));
                return true;
            } else if (itemId == R.id.nav_project) {
                // 跳转到项目页面
                startActivity(new Intent(MainActivity.this, ProjectActivity.class));
                return true;
            } else if (itemId == R.id.nav_settings) {
                // 跳转到设置页面
                startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                return true;
            }
            
            return false;
        });
    }

    private void setupQuickActions() {
        // 邀请好友
        findViewById(R.id.btn_invite_friends).setOnClickListener(v -> {
            Log.d(TAG, "邀请好友按钮被点击");
            Intent intent = new Intent(this, InviteFriendsActivity.class);
            startActivity(intent);
        });

        // 任务中心
        findViewById(R.id.btn_task_center).setOnClickListener(v -> {
            Log.d(TAG, "任务中心按钮被点击");
            Intent intent = new Intent(MainActivity.this, TaskActivity.class);
            startActivity(intent);
        });

        // 悬赏专区
        findViewById(R.id.btn_rewards).setOnClickListener(v -> {
            Log.d(TAG, "悬赏专区按钮被点击");
            Intent intent = new Intent(MainActivity.this, RewardTaskListActivity.class);
            startActivity(intent);
        });
        
        // 记录日志，验证setupQuickActions方法是否被调用
        Log.d(TAG, "setupQuickActions方法被调用，所有快捷操作按钮点击事件已设置");
    }

    private void loadUserData() {
        if (currentUser != null) {
            // 设置用户基本信息
            userNameText.setText(currentUser.getUsername());
            userLevelText.setText(activityManager.getUserActivityLevelName(currentUser.getUsername()));
            
            // 设置用户VIP等级（从用户信息中获取level属性）
            String userLevel = currentUser.getLevel();
            if (userLevel != null && !userLevel.isEmpty()) {
                userVipLevelText.setText(userLevel);
                userVipLevelText.setVisibility(View.VISIBLE);
            } else {
                userVipLevelText.setVisibility(View.GONE);
            }
            
            // 加载用户头像
            CircleImageView userAvatar = findViewById(R.id.user_avatar);
            String avatarUrl = currentUser.getAvatarUrl();
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                // 使用本地路径加载头像
                ImageUtils.loadAvatarIntoImageView(this, userAvatar, avatarUrl);
            } else {
                // 检查是否有保存在本地的头像
                String localAvatarPath = ImageUtils.getUserAvatarPath(this, currentUser.getUsername());
                if (localAvatarPath != null) {
                    // 使用API更新用户头像URL
                    NetworkUtils.updateUserAvatar(currentUser.getUsername(), localAvatarPath);
                    currentUser.setAvatarUrl(localAvatarPath);
                    ImageUtils.loadAvatarIntoImageView(this, userAvatar, localAvatarPath);
                } else {
                    // 使用默认头像
                    userAvatar.setImageResource(R.drawable.default_avatar);
                }
            }
            
            // balance是String类型，需要转换为double
            double balance = 0.0;
            try {
                String balanceStr = currentUser.getBalance();
                if (balanceStr != null && !balanceStr.isEmpty()) {
                    balance = Double.parseDouble(balanceStr);
                }
            } catch (NumberFormatException e) {
                Log.e(TAG, "解析余额失败: " + e.getMessage());
            }
            userBalanceText.setText(String.format("¥ %.2f", balance));
            
            // 设置数据概览
            double todayIncome = activityManager.getTodayIncome(currentUser.getUsername());
            todayIncomeText.setText(String.format("%.2f", todayIncome));
            
            int taskCount = activityManager.getCompletedTaskCount(currentUser.getUsername());
            taskCountText.setText(String.valueOf(taskCount));
            
            // 修改为使用今日下级收益
            double downlineIncome = activityManager.getTodayDownlineIncome(currentUser.getUsername());
            downlineIncomeText.setText(String.format("%.2f", downlineIncome));
            
            // 设置活跃度信息
            ActivityData activityData = activityManager.getActivityData(currentUser.getUsername());
            if (activityData != null) {
                int nextLevelRequired = activityManager.getNextLevelRequiredActivity(currentUser.getUsername());
                if (nextLevelRequired > 0) {
                    activityStatusText.setText(String.format("距离下一等级：%d/%d", 
                            activityData.getMonthlyActivity(), 
                            activityData.getMonthlyActivity() + nextLevelRequired));
                } else {
                    activityStatusText.setText("已达到最高等级");
                }
            } else {
                activityStatusText.setText("暂无活跃度数据");
            }
        } else {
            Log.e(TAG, "当前用户信息为空");
            Toast.makeText(this, "用户信息加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadAnnouncements() {
        // 从API获取公告列表
        List<Announcement> announcementList = activityManager.getAnnouncements(5);
        
        // 设置公告适配器
        announcementAdapter = new AnnouncementAdapter(this, announcementList, this);
        announcementPager.setAdapter(announcementAdapter);
        
        // 设置自动轮播（每5秒切换一次）
        announcementPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            private final long DELAY_MS = 5000;
            private final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    int nextItem = (announcementPager.getCurrentItem() + 1) % announcementAdapter.getItemCount();
                    announcementPager.setCurrentItem(nextItem, true);
                    announcementPager.postDelayed(this, DELAY_MS);
                }
            };

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                announcementPager.removeCallbacks(runnable);
                announcementPager.postDelayed(runnable, DELAY_MS);
            }
        });
        
        // 添加"查看更多"按钮点击事件
        findViewById(R.id.btn_more_announcements).setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, AnnouncementListActivity.class);
            startActivity(intent);
        });
    }

    private void loadHotRewards() {
        // 从API获取热门悬赏列表
        List<RewardTask> hotRewardsList = activityManager.getHotRewards(5);
        
        // 设置热门悬赏适配器
        hotRewardAdapter = new HotRewardAdapter(this, hotRewardsList, this);
        hotRewardsRecyclerView.setAdapter(hotRewardAdapter);
        
        // 添加"查看更多"按钮点击事件
        findViewById(R.id.btn_more_rewards).setOnClickListener(v -> {
            Log.d(TAG, "查看更多悬赏按钮被点击");
            Intent intent = new Intent(MainActivity.this, RewardTaskListActivity.class);
            startActivity(intent);
        });
    }

    private void loadRankingPreview() {
        // 从ActivityManager获取活跃度排行榜前三名
        List<ActivityData> topRankings = activityManager.getActivityDataList(3);
        if (topRankings.size() >= 1) {
            setupRankItem(rankItem1, topRankings.get(0), 1);
        }
        if (topRankings.size() >= 2) {
            setupRankItem(rankItem2, topRankings.get(1), 2);
        }
        if (topRankings.size() >= 3) {
            setupRankItem(rankItem3, topRankings.get(2), 3);
        }
        
        // 添加"查看全部"按钮点击事件
        findViewById(R.id.btn_view_rankings).setOnClickListener(v -> {
            Log.d(TAG, "查看全部排行榜按钮被点击");
            Intent intent = new Intent(MainActivity.this, RankingsActivity.class);
            startActivity(intent);
        });
    }

    private void setupRankItem(View rankItemView, ActivityData activityData, int rank) {
        TextView rankNumber = rankItemView.findViewById(R.id.rank_number);
        TextView userName = rankItemView.findViewById(R.id.user_name);
        TextView userDetail = rankItemView.findViewById(R.id.user_detail);
        TextView activityPoints = rankItemView.findViewById(R.id.activity_points);

        rankNumber.setText(String.valueOf(rank));
        userName.setText(activityData.getUsername());
        userDetail.setText(String.format("连续登录: %d天", activityData.getConsecutiveLogins()));
        activityPoints.setText(String.format("%d分", activityData.getMonthlyActivity()));

        // 根据排名设置不同的背景
        if (rank == 1) {
            rankNumber.setBackgroundResource(R.drawable.bg_achievement_gold);
        } else if (rank == 2) {
            rankNumber.setBackgroundResource(R.drawable.bg_achievement_silver);
        } else if (rank == 3) {
            rankNumber.setBackgroundResource(R.drawable.bg_achievement_bronze);
        }
    }

    @Override
    public void onRewardClick(RewardTask rewardTask) {
        // 点击热门悬赏项
        Intent intent = new Intent(MainActivity.this, RewardDetailActivity.class);
        intent.putExtra("reward_id", rewardTask.getId());
        startActivity(intent);
    }

    @Override
    public void onAnnouncementClick(Announcement announcement) {
        // 点击公告时，跳转到公告详情页面
        Intent intent = new Intent(MainActivity.this, AnnouncementDetailActivity.class);
        intent.putExtra("announcement_id", announcement.getId());
        startActivity(intent);
    }

    private boolean checkDoubleLaunch() {
        // 检查是否是重复启动
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            Log.d(TAG, "检测到重复启动，finish当前Activity实例");
            return true;
        }
        return false;
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: MainActivity恢复");

        if (isNavigating) {
            Log.d(TAG, "onResume: isNavigating=true，避免执行操作");
            return;
        }

        if (checkLoginStatusWithoutRedirect()) {
            loadUserData();
            loadHotRewards();
        } else {
            Log.d(TAG, "onResume: 登录状态无效，但不自动跳转");
        }
    }

    private boolean checkLoginStatus() {
        Log.d(TAG, "检查登录状态");
        boolean isLoggedIn = prefs.getBoolean(KEY_IS_LOGGED_IN, false);
        String token = NetworkUtils.getAuthToken(this);
        String userType = prefs.getString(KEY_USER_TYPE, "");
        
        Log.d(TAG, "登录状态检查: isLoggedIn=" + isLoggedIn + ", token=" + (token != null ? "有效" : "无效") + ", userType=" + userType);
        
        // 在线模式的验证逻辑
        if (!isLoggedIn || token == null || token.isEmpty()) {
            navigateToLogin();
            return false;
        }
        
        // 如果是管理员，跳转到管理员界面
        if ("admin".equals(userType)) {
            Log.d(TAG, "当前用户为管理员，跳转到管理员界面");
            navigateToAdmin();
            return false;
        }

        Log.d(TAG, "登录状态有效，允许访问MainActivity");
        return true;
    }

    private boolean checkLoginStatusWithoutRedirect() {
        boolean isLoggedIn = prefs.getBoolean(KEY_IS_LOGGED_IN, false);
        String token = NetworkUtils.getAuthToken(this);
        Log.d(TAG, "checkLoginStatusWithoutRedirect: isLoggedIn=" + isLoggedIn + ", token有效=" + (token != null && !token.isEmpty()));
        return isLoggedIn && token != null && !token.isEmpty();
    }

    private void navigateToLogin() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        
        isNavigating = true;
        
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        
        isNavigating = false;
    }

    private void navigateToAdmin() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }

        isNavigating = true;

        Intent intent = new Intent(this, AdminActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();

        isNavigating = false;
    }
}